package com.atguigu.tingshu.comment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.comment.service.CommentService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.kafka.KafkaMessagePojo;
import com.atguigu.tingshu.model.comment.Comment;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.comment.CommentVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.alibaba.nacos.client.config.utils.ParamUtils.checkContent;

@Service
public class CommentServiceImpl implements CommentService {

	@Autowired
	private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

  /**
   * 保存评论
   * @param commentVo
   * @return
   */
  @Override
  public void save(CommentVo commentVo) {
    //获取用户id
    Long userId = AuthContextHolder.getUserId();
    //mongo的do初始化
    Comment comment = new Comment();
    //评论的主键
    comment.setId(IdWorker.getIdStr());
    //专辑
    comment.setAlbumId(commentVo.getAlbumId());
    //声音
    comment.setTrackId(commentVo.getTrackId());
    //用户
    comment.setUserId(userId);
    //内容
    comment.setContent(commentVo.getContent());
    //回复id
    comment.setReplyCommentId(commentVo.getReplyCommentId());
    //点赞量 初始为0
    comment.setPraiseCount(0);
    //评分
    comment.setAlbumCommentScore(commentVo.getAlbumCommentScore());
    //日期
    comment.setCreateTime(new Date());
    //状态:0101-未审核 0102-审核通过 0103-需要人工审核
    comment.setIsPassed("0101");
    //评论保存
    String collectName = null;
    if(commentVo.getReplyCommentId().equals("0")){
      //保存评论: 同步保存评论到mongo数据库
      collectName = "user_comment_" + commentVo.getTrackId();
    }else{
      //回复保存
      collectName = "user_comment_reply_" + commentVo.getReplyCommentId();
    }
    mongoTemplate.save(comment, collectName);
    //发送消息: 异步通知消费者监听消息对评论内容进行审核
    rabbitTemplate.convertAndSend("comment_exchange", "track.comment", comment.getId() + ":"  + collectName);
  }

  @Autowired
  private KafkaTemplate kafkaTemplate;
  /**
   * 审核评论: 异步执行
   * @param commentId
   */
  @SneakyThrows
  @Override
  public void checkCommentContent(String commentId) {
    //切分 commentId:collectName
    String[] split = commentId.split(":");
    //查询评论的详细信息
    Comment comment =
            mongoTemplate.findById(split[0], Comment.class, split[1]);
    //判断
    if(comment.getIsPassed().equals("0101")){
      //只处理未审核的
      String content = comment.getContent();
      //调用第三方审核接口进行审核
      if(checkContent(content)){
        //审核通过,补全用户信息,修改审核状态
        comment.setIsPassed("0102");
        UserInfo userInfo =
                userInfoFeignClient.getUserInfo(comment.getUserId());
        comment.setNickname(userInfo.getNickname());
        comment.setAvatarUrl(userInfo.getAvatarUrl());
        //发送行为消息
        KafkaMessagePojo kafkaMessagePojo = new KafkaMessagePojo();
        kafkaMessagePojo.setAlbumId(comment.getAlbumId());
        kafkaMessagePojo.setType("comment");
        kafkaTemplate.send("tingshu_stream_rank_topic", JSONObject.toJSONString(kafkaMessagePojo));
      }else{
        //审核不通过: 转人工审核
        comment.setIsPassed("0103");
      }
      //保存到mongo
      mongoTemplate.save(comment, split[1]);
    }
  }

  /**
   * mock调用腾讯云内容审核接口
   * @param content
   * @return
   */
  private static Boolean checkContent(String content){
    if(content.contains("尚硅谷")){
      return true;
    }else{
      return false;
    }
  }

  /**
   * 分页条件查询评论列表
   * @param albumId
   * @param trackId
   * @param page
   * @param size
   * @return
   */
  @Override
  public Object findCommentPage(Long albumId, Long trackId, Integer page, Integer size) {
    //查询评论的集合名字
    String collectName = "user_comment_" + trackId;
    //查询条件
    Query query = Query.query(
                               Criteria.where("albumId").is(albumId)
                                       .and("trackId").is(trackId)
                                       .and("isPassed").is("0102"))
                        // .limit(size).skip((page - 1) * size)
                       .with(PageRequest.of(page-1, size))
                       .with(Sort.by(Sort.Direction.DESC, "createTime"));
    //分页查询列表:评论列表
    List<Comment> commentList = mongoTemplate.find(query, Comment.class, collectName);
    //查询每个评论的回复
    commentList = commentList.stream().map(comment -> {
      //获取评论的回复的集合名字
      String replyCollectName = "user_comment_reply_" + comment.getId();
      //查询这个评论的回复集合
      List<Comment> replyList =
              mongoTemplate.find(
                      Query.query(Criteria.where("isPassed").is("0102"))
                           .with(Sort.by(Sort.Direction.DESC, "createTime")),
                      Comment.class,
                      replyCollectName);
      //保存
      comment.setReplyCommentList(replyList);
      //返回
      return comment;
    }).collect(Collectors.toList());
    //包装返回结果
    IPage<Comment> result = new Page<>(page, size);
    result.setRecords(commentList);
    long count = mongoTemplate.count(query, collectName);
    result.setTotal(count);
    //返回结果
    return result;
  }





}
